package com.my.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.entity.GradeClass;
import com.my.entity.User;
import com.my.entity.UserCurriculum;
import com.my.entity.UserGradeClass;
import com.my.service.*;
import com.my.util.Rest;
import com.my.util.execl.StudentExcelListener;
import com.my.util.execl.TeacherExcelListener;
import com.my.util.execl.entity.CurriculumExecl;
import com.my.util.execl.entity.TeacherExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("teacher")
public class TeacherController {

    @Autowired
    private UserService service;

    @Autowired
    private GradeClassService gcService;

    @Autowired
    private CurriculumService cService;

    @Autowired
    private UserCurriculumService ucService;

    @Autowired
    private UserGradeClassService ugcService;

    @GetMapping("list")
    public String list(Model model, @RequestParam(defaultValue = "1") int pageNo, User user) {
        model.addAttribute("page", service.page(new Page<>(pageNo, 10), new QueryWrapper<User>().
                eq(user.getSex() != null, "sex", user.getSex()).
                like(StrUtil.isNotBlank(user.getName()), "name", user.getName())
                .in("type", 1, 2)));
        model.addAttribute("name", user.getName());
        model.addAttribute("sex", user.getSex());
        return "teacher/list";
    }

    @GetMapping("edit")
    public String edit(Model model, Long id) {
        model.addAttribute("gradeList", gcService.list(new QueryWrapper<GradeClass>().eq("deep", 1)));
        if(id != null) {
            model.addAttribute("teacher", service.getById(id));
        }
        return "teacher/edit";
    }

    @PostMapping("edit")
    @ResponseBody
    public Rest edit(User user) {
        if(user.getOldId() == null && StrUtil.isBlank(user.getPassword())) {
            user.setPassword("123456");
        }
        if(StrUtil.isNotBlank(user.getPassword())) {
            user.setPassword(SecureUtil.md5(user.getPassword()));
        }
        if(user.getOldId() == null ? service.save(user) : (user.getOldId().equals(user.getId()) && service.updateById(user))) {
            return Rest.ok("保存成功！");
        }
        Long oldId = user.getId();
        user.setId(user.getOldId());
        if(service.updateById(user) && service.update(new UpdateWrapper<User>().set("id", oldId).eq("id", user.getId()))) {
            return Rest.ok("保存成功！");
        }
        return Rest.err("保存失败！");
    }

    @PostMapping("del")
    @ResponseBody
    public Rest del(Long id) {
        if(service.removeById(id)) {
            return Rest.ok("删除成功！");
        }
        return Rest.err("删除失败！");
    }

    @GetMapping("course")
    public String course(Model model, Long id) {
        model.addAttribute("id", id);
        model.addAttribute("rList", ucService.list(new QueryWrapper<UserCurriculum>().eq("user_id", id)).stream().map(UserCurriculum::getCurriculumId).collect(Collectors.toList()));
        model.addAttribute("cList", JSONUtil.toJsonStr(cService.list()));
        return "teacher/course";
    }

    @PostMapping("course")
    @ResponseBody
    @Transactional
    public Rest course(Long id, @RequestParam(value = "cs[]") Long[] cs) {
        ucService.remove(new QueryWrapper<UserCurriculum>().eq("user_id", id));
        for (Long s : cs) {
            ucService.save(new UserCurriculum().setUserId(id).setCurriculumId(s));
        }
        return Rest.ok("修改成功");
    }

    @GetMapping("manageClass")
    public String manageClass(Model model, Long id) {
        model.addAttribute("id", id);
        model.addAttribute("rList", ugcService.list(new QueryWrapper<UserGradeClass>().eq("user_id", id)).stream().map(UserGradeClass::getGradeClassId).collect(Collectors.toList()));
        model.addAttribute("cList", JSONUtil.toJsonStr(gcService.getByDeep2()));
        return "teacher/manageClass";
    }

    @PostMapping("manageClass")
    @ResponseBody
    @Transactional
    public Rest manageClass(Long id, @RequestParam(value = "mc[]") Long[] mc) {
        ugcService.remove(new QueryWrapper<UserGradeClass>().eq("user_id", id));
        for (Long s : mc) {
            ugcService.save(new UserGradeClass().setUserId(id).setGradeClassId(s));
        }
        return Rest.ok("修改成功");
    }

    @PostMapping("import")
    @ResponseBody
    @Transactional
    public Rest importData(@RequestParam("file") MultipartFile file) {
        if(file.isEmpty()) {
            return Rest.err("上传文件不能为空!");
        }
        String fileName = file.getOriginalFilename();
        if(fileName.lastIndexOf(".") == -1) {
            return Rest.err("请上传正确的文件!");
        }
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
        if(!(suffixName.toLowerCase().equals("xls") || suffixName.toLowerCase().equals("xlsx"))) {
            return Rest.err("该文件格式不支持！");
        }
        try {
            EasyExcel.read(file.getInputStream(), TeacherExcel.class, new TeacherExcelListener(service, gcService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
            return Rest.err("请检查导入文件数据格式！");
        }
        return Rest.ok("导入成功！");
    }

    @GetMapping("/exist")
    @ResponseBody
    public Rest exist(Long id) {
        return Rest.ok().setData("exist", service.getById(id));
    }

}
